<template>
   <!-- 弹窗组件 -->
   <div class="dialog-box">
      <el-dialog
         v-model="dialogVisible"
         :title="form.id ? '编辑退货单' : '新增退货单'"
         width="900"
      >
         <el-form
            :model="form"
            label-width="100px"
         >
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="关联采购单"
                     required
                  >
                     <el-input
                        v-model="form.return_no"
                        placeholder="请选择"
                        suffix-icon="MoreFilled"
                        @focus="openSelectSuppliersPopup"
                     />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item
                     label="类型"
                     required
                  >
                     <el-input
                        v-model="form.purchase_order_type_text"
                        placeholder="补库单类型"
                     />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="退货负责人"
                     required
                  >
                     <el-input
                        v-model="form.manager_name"
                        placeholder="请选择"
                        suffix-icon="MoreFilled"
                        @focus="openPurchasingDirectorPopup"
                     />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item
                     label="负责人电话"
                     required
                  >
                     <el-input
                        v-model="form.manager_phone"
                        placeholder="根据所选负责人带出"
                     />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="退货日期"
                     required
                  >
                     <el-date-picker
                        type="date"
                        v-model="form.created_at"
                        placeholder="请选择"
                     />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item
                     label="备注"
                     required
                  >
                     <el-input
                        v-model="form.note"
                        placeholder="请输入"
                     />
                  </el-form-item>
               </el-col>
            </el-row>
            <div class="supply-products">
               <div class="title">
                  <div class="title-text">
                     <div class="line"></div>
                     退货产品
                  </div>
               </div>
               <el-table
                  border
                  :data="form.purchase_return_item"
                  style="width: 100%"
               >
                  <el-table-column
                     prop="spu_name"
                     label="产品名称"
                     width="160"
                  >
                     <template #default="scope">
                        <span>{{ scope.row.spu_name ? scope.row.spu_name : scope.row.name }}</span>
                     </template>
                  </el-table-column>
                  <el-table-column
                     prop="specification"
                     label="规格型号"
                     width="160"
                  />
                  <el-table-column
                     prop="product_no"
                     label="产品编号"
                     width="160"
                  />
                  <el-table-column
                     prop="measure_unit_name"
                     label="采购单位"
                     width="160"
                  />
                  <el-table-column
                     prop="num"
                     label="采购数量"
                     width="160"
                  >
                  </el-table-column>
                  <el-table-column
                     prop="stock_num"
                     label="库存数量"
                     width="160"
                  >
                  </el-table-column>
                  <el-table-column
                     prop="price"
                     label="采购单价(元)"
                     width="160"
                  />
                  <el-table-column
                     prop="return_num"
                     label="退货数量"
                     width="160"
                  >
                     <template #default="scope">
                        <el-input
                           v-model="scope.row.return_num"
                           placeholder="请输入"
                           @input="handleReturnNumChange(scope.row)"
                        />
                     </template>
                  </el-table-column>
                  <el-table-column
                     prop="total_price"
                     label="退货金额"
                     width="100"
                  />
               </el-table>
            </div>
            <div class="supply-products">
               <div class="title">
                  <div class="title-text">
                     <div class="line"></div>
                     价格设置
                  </div>
               </div>
               <el-row :gutter="20">
                  <el-col :span="12">
                     <el-form-item label="采购整单折扣（%）">
                        <el-input
                           v-model="form.return_discount"
                           placeholder="请输入"
                           @input="handleDiscountChange"
                        />
                     </el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="退货总金额(元)">
                        <el-input
                           v-model="form.total_amount"
                           placeholder="请输入"
                           disabled
                        />
                     </el-form-item>
                  </el-col>
               </el-row>
            </div>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="dialogVisible = false">取消</el-button>
               <el-button
                  color="#626aef"
                  @click="handleSubmit"
               >
                  确定
               </el-button>
            </div>
         </template>
      </el-dialog>
      <!-- 关联采购单 -->
      <AssociatedPurchaseOrder
         ref="associatedPurchaseOrderRef"
         @handleSelectAssociatedPurchaseOrder="handleSelectAssociatedPurchaseOrder"
      />
      <!-- 选择退货负责人 -->
      <SelectPurchasingDirector
         ref="selectPurchasingDirectorRef"
         @selectPurchasingDirector="handleSelectPurchasingDirector"
      />
   </div>
</template>

<script setup lang="ts">
   import { ref, reactive, watch, WatchStopHandle, computed } from "vue";
   import SelectPurchasingDirector from "./SelectPurchasingDirector.vue";
   import api from "@/api/index.js";
   import AssociatedPurchaseOrder from "./AssociatedPurchaseOrder.vue";
   import { ElMessage } from "element-plus";
   const associatedPurchaseOrderRef = ref<any>(null); // 关联采购单弹窗
   const selectPurchasingDirectorRef = ref<any>(null); // 选择采购负责人弹窗
   const dialogVisible = ref<boolean>(false); // 弹窗控制器
   const purchase_order_item = ref<any>([]); // 采购订单详情
   const emit = defineEmits<{
      (e: "init"): void;
   }>();
   const form = ref<any>({
      id: null, //采购退货ID
      return_no: "", //退货编号
      purchase_order_id: 0, //关联采购单ID
      total_amount: "0.00", //总金额
      return_discount: "100", //整体折扣，默认100%
      return_date: "", //退货日期
      manager_member_id: 0, //采购负责人ID
      manager_name: "", //采购负责人名称
      manager_phone: "", //负责人电话
      status: 0, //状态（0：待提交，1：审核中，2：审核完成，3：审核拒绝）
      note: "", //备注
      creator_name: "", //创建人姓名
      audit_name: "", //审核人姓名
      audit_note: "", //审核备注
      audit_at: "", //审核
      created_at: "", //创建时间
      purchase_order_type_text: "", //补库单类型
      status_text: "", //状态
      purchase_return_item: [
         {
            id: 0, //退货产品ID
            return_id: 0, //退货ID
            spu_id: 0, //退货产品spu ID
            spu_name: "", //退货产品spu 名称
            supplier_id: 0, //退货产品供应商ID
            supplier_name: "", //退货产品供应商名称
            product_id: 0, //退货产品ID
            product_no: "", //退货产品编号
            product_name: "", //退货产品名称
            measure_unit_id: 0, //退货产品采购单位
            open_unit_id: 0, //退货产品拆零单位
            open_unit_num: 0, //退货产品拆零单位数量
            spu_measure_unit_id: 0, //退货产品规格单位
            unit_num: 0, //退货产品规格单位
            specification: "", //规格
            price: "", //采购单价
            num: "", //采购
            total_price: "0.00", //采购总价
            stock_num: "", //库存
            return_price: "", //退货单价
            return_num: "0", //退货数量
            created_at: "", //创建时间
         },
      ], //退货产品列表
   });
   // 获取退货单详情
   const getReturnDetail = async (id?: number) => {
      const res = await api.procurement.purchaseReturnDetail({
         id: id,
      });
      if (res.code === 200) {
         form.value = { ...res.data };
         // 获取详情后重新计算总金额
         calculateTotalAmount();
      }
   };
   // 订单详情
   const getPurchaseOrderDetail = async () => {
      const res = await api.procurement.purchaseReturnProductList({
         id: form.value.purchase_order_id,
      });
      if (res.code === 200) {
         form.value.purchase_return_item = res.data.map((item: any) => {
            const returnPrice = parseFloat(item.final_price || item.price || 0).toFixed(2);
            return {
               spu_id: item.spu_id || 0,
               spu_name: item.spu_name, //产品名称
               specification: item.specification, //规格型号
               measure_unit_name: item.measure_unit_name, //采购单位
               num: item.num, //采购数量
               stock_num: item.warehouse_stock_num, //库存数量
               price: parseFloat(item.price || 0).toFixed(2), //采购单价
               return_price: returnPrice, //退货单价
               return_num: "0", // 初始退货数量为0
               total_price: "0.00", // 初始退货金额为0
               product_id: item.product_id || 0,
               product_no: item.product_no,
            };
         });
         // 初始化后计算总金额
         calculateTotalAmount();
      }
   };
   const openLoading = (id?: number) => {
      dialogVisible.value = true;
      if (id) {
         getReturnDetail(id);
      } else {
         form.value = {
            id: null,
            return_no: "",
            purchase_order_id: 0,
            total_amount: "0.00",
            return_discount: "100",
            return_date: "",
            manager_member_id: 0,
            manager_name: "",
            manager_phone: "",
            status: 0,
            note: "",
            created_at: "",
            purchase_return_item: [],
         };
      }
   };

   // 监听器相关变量
   let stopWatch: WatchStopHandle | null = null;

   // 计算单个产品的退货金额
   const calculateItemTotalPrice = (item: any) => {
      if (!item.return_num || !item.return_price) {
         item.total_price = "0.00";
         return "0.00";
      }

      const returnNum = parseFloat(item.return_num) || 0;
      const returnPrice = parseFloat(item.return_price) || 0;

      if (returnNum <= 0 || returnPrice <= 0) {
         item.total_price = "0.00";
         return "0.00";
      }

      const totalPrice = (returnNum * returnPrice).toFixed(2);
      item.total_price = totalPrice;
      return totalPrice;
   };

   // 计算所有产品的退货总金额
   const calculateTotalAmount = () => {
      if (!form.value.purchase_return_item || form.value.purchase_return_item.length === 0) {
         form.value.total_amount = "0.00";
         return;
      }

      // 先计算每个产品的退货金额
      form.value.purchase_return_item.forEach((item: any) => {
         calculateItemTotalPrice(item);
      });

      // 计算总金额并应用折扣
      let totalAmount = form.value.purchase_return_item.reduce((sum: number, item: any) => {
         return sum + parseFloat(item.total_price || 0);
      }, 0);

      // 应用折扣
      if (form.value.return_discount) {
         const discount = parseFloat(form.value.return_discount) / 100;
         if (discount >= 0 && discount <= 1) {
            totalAmount = totalAmount * discount;
         }
      }

      form.value.total_amount = totalAmount.toFixed(2);
   };

   // 处理退货数量变化
   const handleReturnNumChange = (item: any) => {
      // 验证退货数量不能超过库存数量
      const returnNum = parseFloat(item.return_num || 0);
      const stockNum = parseFloat(item.stock_num || 0);

      if (returnNum > stockNum) {
         ElMessage.warning("退货数量不能超过库存数量");
         item.return_num = stockNum.toString();
      }

      // 确保退货数量不为负
      if (returnNum < 0) {
         item.return_num = "0";
      }

      // 验证小数位数不能超过4位
      const decimalPlaces = (returnNum.toString().split(".")[1] || "").length;
      if (decimalPlaces > 4) {
         ElMessage.warning("小数位数不能超过4位");
         item.return_num = returnNum.toFixed(4);
      }

      // 计算该项的总价
      calculateItemTotalPrice(item);

      // 重新计算总金额
      calculateTotalAmount();
   };

   // 处理折扣变化
   const handleDiscountChange = () => {
      // 验证折扣范围
      const discount = parseFloat(form.value.return_discount || 0);

      if (discount < 0) {
         form.value.return_discount = "0";
      } else if (discount > 100) {
         form.value.return_discount = "100";
      }

      // 重新计算总金额
      calculateTotalAmount();
   };

   // 选择关联采购单
   const openSelectSuppliersPopup = (e: any) => {
      // 开始监听purchase_order_id变化
      if (!stopWatch) {
         stopWatch = watch(
            () => form.value.purchase_order_id,
            () => {
               getPurchaseOrderDetail();
            }
         );
      }
      associatedPurchaseOrderRef.value.openLoading();
      e.target.blur();
   };

   // 选择退货负责人
   const openPurchasingDirectorPopup = (e: any) => {
      const flag: number = 1; //退货
      selectPurchasingDirectorRef.value.openLoading(flag);
      e.target.blur();
   };

   // 验证表单数据
   const validateForm = () => {
      if (!form.value.purchase_order_id) {
         ElMessage.error("请选择关联采购单");
         return false;
      }

      if (!form.value.manager_member_id) {
         ElMessage.error("请选择退货负责人");
         return false;
      }

      if (!form.value.created_at) {
         ElMessage.error("请选择退货日期");
         return false;
      }

      // 检查是否有退货产品
      if (!form.value.purchase_return_item || form.value.purchase_return_item.length === 0) {
         ElMessage.error("没有退货产品");
         return false;
      }

      // 检查是否有退货数量
      const hasReturnNum = form.value.purchase_return_item.some((item: any) => {
         return parseFloat(item.return_num) > 0;
      });

      if (!hasReturnNum) {
         ElMessage.error("请至少输入一个产品的退货数量");
         return false;
      }

      // 检查退货数量是否超过库存数量
      const invalidReturnNum = form.value.purchase_return_item.some((item: any) => {
         return parseFloat(item.return_num) > parseFloat(item.stock_num);
      });

      if (invalidReturnNum) {
         ElMessage.error("退货数量不能超过库存数量");
         return false;
      }

      return true;
   };

   // 处理表单提交
   const handleSubmit = async () => {
      if (!validateForm()) {
         return;
      }
      // 格式化日期为YYYY-MM-DD
      let formattedDate = "";
      if (form.value.created_at instanceof Date) {
         const year = form.value.created_at.getFullYear();
         const month = String(form.value.created_at.getMonth() + 1).padStart(2, "0");
         const day = String(form.value.created_at.getDate()).padStart(2, "0");
         formattedDate = `${year}-${month}-${day}`;
      } else if (typeof form.value.created_at === "string") {
         // 处理ISO日期字符串格式 (如 "2025-07-08T16:00:00.000Z")
         const dateObj = new Date(form.value.created_at);
         if (!isNaN(dateObj.getTime())) {
            const year = dateObj.getFullYear();
            const month = String(dateObj.getMonth() + 1).padStart(2, "0");
            const day = String(dateObj.getDate()).padStart(2, "0");
            formattedDate = `${year}-${month}-${day}`;
         }
      }

      // 构建提交数据
      const submitData = {
         purchase_order_id: form.value.purchase_order_id,
         manager_member_id: form.value.manager_member_id,
         return_date: formattedDate,
         note: form.value.note,
         return_goods: form.value.purchase_return_item
            .filter((item: any) => parseFloat(item.return_num) > 0)
            .map((item: any) => {
               return {
                  no: item.product_no,
                  return_num: item.return_num,
               };
            }),
      };
      if (form.value.id) {
         const res = await api.procurement.purchaseReturnUpdate({ ...submitData, id: form.value.id });
         if (res.code === 200) {
            ElMessage.success("退货单提交成功");
            dialogVisible.value = false;
         } else {
            ElMessage.error(res.message || "提交失败");
         }
         emit("init");
      } else {
         // 提交数据
         const res = await api.procurement.purchaseReturnCreate(submitData);

         if (res.code === 200) {
            ElMessage.success("退货单提交成功");
            dialogVisible.value = false;
            // 可以添加刷新列表的回调
         } else {
            ElMessage.error(res.message || "提交失败");
         }
         emit("init");
      }
   };

   interface AssociatedPurchaseOrder {
      name: string;
      id: number;
      order_no: string;
      type_text: string;
   }

   // 处理选择关联采购单
   const handleSelectAssociatedPurchaseOrder = (associatedPurchaseOrder: AssociatedPurchaseOrder) => {
      form.value.purchase_order_id = associatedPurchaseOrder.id;
      form.value.return_no = associatedPurchaseOrder.order_no;
      form.value.purchase_order_type_text = associatedPurchaseOrder.type_text;
   };
   interface PurchasingDirector {
      Sname: string;
      name: string;
      Sphone: string;
      Sposition: string;
      id: number;
      mobile: string;
   }
   // 处理选择采购负责人
   const handleSelectPurchasingDirector = (purchasingDirector: PurchasingDirector) => {
      form.value.manager_member_id = purchasingDirector.id;
      form.value.manager_name = purchasingDirector.name;
      form.value.manager_phone = purchasingDirector.mobile;
   };

   // 监听退货数量变化
   watch(
      () => form.value.purchase_return_item,
      () => {
         calculateTotalAmount();
      },
      { deep: true }
   );

   // 监听折扣变化
   watch(
      () => form.value.return_discount,
      () => {
         handleDiscountChange();
      }
   );

   defineExpose({
      openLoading,
      handleReturnNumChange,
      handleDiscountChange,
   });
</script>

<style lang="scss" scoped>
   ::v-deep .el-dialog {
      --el-dialog-padding-primary: 0px;
   }
   ::v-deep .el-dialog__header {
      padding: 10px 16px;
      border-bottom: 1px solid #f0f0f0;
      font-weight: bold;
   }
   ::v-deep .dialog-footer {
      padding: 10px 16px;
      border-top: 1px solid #f0f0f0;
   }
   ::v-deep .el-dialog__headerbtn .el-dialog__close {
      color: #000;
   }
   ::v-deep .el-dialog__body {
      padding: 10px 10px;
   }
   :deep(.el-form-item__label) {
      justify-content: flex-start;
   }
   :deep(.el-form-item) {
      flex-direction: column;
      margin-bottom: 7px;
   }
   :deep(.el-select__wrapper) {
      background: #fafcfb;
   }
   :deep(.el-badge__content.is-fixed) {
      color: #666;
      border-radius: 3px;
      padding: 4px;
   }
   :deep(.el-table .cell) {
      display: flex;
      justify-content: center;
   }
   :deep(.el-button:hover) {
      color: #6860ff;
      background: #f4f5f7;
   }
   :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
      width: 100%;
   }
   :deep(.el-input__wrapper:hover) {
      box-shadow: inset 0 0 0 1px #6860ff;
   }
   .supply-products {
      margin-top: 20px;
      .title {
         display: flex;
         align-items: center;
         justify-content: space-between;
         margin-bottom: 10px;
         font-weight: bold;
         .title-text {
            display: flex;
            align-items: center;
            .line {
               height: 17px;
               width: 2px;
               border-radius: 12px;
               margin-right: 8px;
               background-color: #6860ff;
            }
         }
      }
   }
   .image-list {
      display: flex;
      gap: 8px;
      .el-image {
         width: 40px;
         height: 40px;
         border-radius: 4px;
      }
   }
</style>
